<template>
  <div class="cert-manage">
    <el-form :inline="true">
      <el-form-item>
        <el-button-group>
          <el-button type="primary" @click="openEditor()" icon="el-icon-plus">新增</el-button>
          <el-button type="primary" @click="openSearch()" icon="el-icon-search">搜索</el-button>
          <el-button type="primary" @click="openSettings()" icon="el-icon-setting">到期提醒</el-button>
        </el-button-group>
      </el-form-item>

      <el-form-item>
        <el-button-group>
          <el-button type="primary" icon="el-icon-upload2" @click="onImportClick()">导入</el-button>
          <el-button type="primary" icon="el-icon-download" @click="downloadExcel()">导出</el-button>
        </el-button-group>
      </el-form-item>

      <el-form-item>
        <el-button
          type="danger"
          @click="multipleDelete()"
          :disabled="multipleSelections.length <= 0"
        >批量删除</el-button>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" @click="openCertNameManager">证件名称</el-button>
      </el-form-item>
    </el-form>

    <cert-search
      ref="certSearch"
      :page-index="pageIndex"
      :page-size="pageSize"
      @onSearched="onSearched"
      @onCancel="cancelSearch"
    />    

    <el-table
      :data="dataList"
      border
      v-loading="dataListLoading"
      @selection-change="onSelectionChange"
      style="width: 100%;"
    >
      <el-table-column type="selection" width="55" align="center"></el-table-column>
      <el-table-column type="index" header-align="center" align="center" label="序号" />
      <el-table-column width="150" prop="realname" header-align="center" align="center" label="姓名" />
      <el-table-column width="150" prop="deptName" header-align="center" align="center" label="部门" />
      <el-table-column width="150" prop="craft" header-align="center" align="center" label="证件工种" />
      <el-table-column
        width="150"
        prop="certType"
        header-align="center"
        align="center"
        label="证件类型"
      />
      <el-table-column
        width="200"
        prop="certName"
        header-align="center"
        align="center"
        label="证件名称"
      />
      <el-table-column
        width="200"
        prop="certNumber"
        header-align="center"
        align="center"
        label="证件号码"
      />
      <el-table-column
        width="200"
        prop="certStartTime"
        header-align="center"
        align="center"
        label="使用起始时间"
      />
      <el-table-column
        width="200"
        prop="certEndTime"
        header-align="center"
        align="center"
        label="使用截止时间"
      />
      <el-table-column header-align="center" align="center" label="操作">
        <template slot-scope="scope">
          <el-button type="text" @click="openEditor(scope.row)">编辑</el-button>
          <el-button type="text" @click="deleteById(scope.row.id)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <el-pagination
      @size-change="onPageSizeChange"
      @current-change="loadCretList"
      :current-page.sync="pageIndex"
      :page-size="pageSize"
      :total="totalCount"
      :page-sizes="[10, 20]"
      layout="total, sizes, prev, pager, next, jumper"
    ></el-pagination>

    <batch-import
      v-if="batchImportVisible"
      ref="batchImport"
      message="一次最多导入200条数据"
      @uploadFile="importFile"
    />

    <cert-editor ref="certEditor" @refresh="loadCretList()" />

    <cert-name-manager ref="certNameManager" />
  </div>
</template>

<script>
import BatchImport from '../questions/batchimport'
import CertSearch from './cert-search'
import CertEditor from './cert-editor'
import CertNameManager from './cert-name-manager'

export default {
  components: {
    BatchImport,
    CertSearch,
    CertEditor,
    CertNameManager
  },
  data() {
    return {
      isSearch: false,
      searchCondition: {},
      dataList: [],
      pageIndex: 1,
      pageSize: 10,
      totalCount: 0,
      dataListLoading: false,
      multipleSelections: [],
      batchImportVisible: false,
      certTypeNameVisible: false,
      certDays: 0
    }
  },
  // components: {edit},
  mounted() {
    this.loadCretList()
  },
  methods: {
    openCertNameManager () {
      this.$refs.certNameManager.open()
    },
    async openSettings() {
      let res = await this.$http.post(
        '/usercenter-admin/certConfig/getCertConfig'
      )
      this.certDays = res.data || 0
      this.$prompt(
        `请输入到期提醒天数，当前设置天数为${this.certDays}天`,
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          inputPattern: /^[0-9]+$/,
          inputErrorMessage: '请输入正整数',
          inputValue: this.certDays
        }
      ).then(async ({ value }) => {
        let saveRes = await this.$http.post(
          '/usercenter-admin/certConfig/save',
          { alertDays: value }
        )
        if (saveRes.code === 200) {
          this.$notify.success({
            title: '成功',
            message: '保存到期提醒天数成功'
          })
          this.$store.dispatch('user/loadAlertListCount')
        }
      })
    },
    openSearch() {
      this.pageIndex = 1
      this.isSearch = true
      this.$refs.certSearch.open()
    },
    cancelSearch() {
      this.isSearch = false
      this.searchCondition = {}
      this.pageIndex = 1
      this.loadCretList()
    },
    onSearched(condition) {
      this.isSearch = true
      this.searchCondition = condition
      this.pageIndex = 1
      this.loadCretList()
    },
    openEditor(cert) {
      if (cert) {
        this.$refs.certEditor.open({ id: cert.id, readonly: false })
      } else {
        this.$refs.certEditor.open({ id: '', readonly: false })
      }
    },
    onPageSizeChange(val) {
      this.pageSize = val
      this.pageIndex = 1
      this.loadCretList()
    },
    onSelectionChange(val) {
      this.multipleSelections = val
    },
    onImportClick() {
      this.batchImportVisible = true
      this.$nextTick(() => this.$refs.batchImport.init(5))
    },
    // 获取数据列表
    async loadCretList() {
      var request = {
        page: this.pageIndex,
        limit: this.pageSize
      }
      if (this.isSearch) {
        request = Object.assign(
          JSON.parse(JSON.stringify(this.searchCondition)),
          request
        )
        delete request.deptIds
      }
      this.dataListLoading = true
      let res = await this.$http.post(
        '/usercenter-admin/certManage/list',
        request
      )

      if (res.code === 200) {
        this.dataList = res.data.list
        this.totalCount = res.data.totalCount
      } else {
        this.$notify.error({
          title: '失败',
          message: '加载证件列表失败，请重试！'
        })
      }
      this.dataListLoading = false
    },
    async multipleDelete() {
      let confirm = await this.$confirm('您确认这些证件吗？', '提示', {
        cancelButtonText: '取消',
        confirmButtonText: '确认'
      })
      if (confirm !== 'confirm') return

      let loading = this.$loading({
        lock: true,
        text: 'Loading',
        spinner: 'el-icon-loading',
        background: 'rgba(255, 255, 255, 0.7)'
      })
      let ids = this.multipleSelections.map(x => x.id).join(',')
      let res = await this.$http.post('/usercenter-admin/certManage/delete', {
        ids: ids
      })
      if (res && res.code === 200) {
        this.$notify.success({ title: '成功', message: '删除人员证件成功' })
        this.$store.dispatch('user/loadAlertListCount')
        await this.loadCretList()
      } else {
        this.$notify.error({ title: '错误', message: res.msg })
      }
      loading.close()
    },
    async deleteById(id) {
      let confirm = await this.$confirm('您确认删除此条证件吗？', '提示', {
        cancelButtonText: '取消',
        confirmButtonText: '确认'
      })
      if (confirm !== 'confirm') return

      let res = await this.$http.post(
        '/usercenter-admin/certManage/deleteById',
        { id: id }
      )
      if (res && res.code === 200) {
        this.$notify.success({ title: '成功', message: '删除人员证件成功' })
        this.$store.dispatch('user/loadAlertListCount')
        await this.loadCretList()
      } else {
        this.$notify.error({ title: '错误', message: res.msg })
      }
    },
    /* 导入导出 */
    async importFile(file) {
      let Loading = this.$loading({
        lock: true,
        text: 'Loading',
        spinner: 'el-icon-loading',
        background: 'rgba(255, 255, 255, 0.7)'
      })
      let formData = new FormData()
      formData.append('file', file)

      let res = await this.$http.post('/usercenter-admin/import/cert', formData)
      if (res && res.code === 200) {
        this.$notify.success({ title: '成功', message: '导入证件列表成功' })
        this.batchImportVisible = false
        this.pageIndex = 1
        this.loadCretList()
      } else {
        this.$notify.error({
          title: '失败',
          message: '导出证件列表失败，请重试！'
        })
      }
      Loading.close()
    },
    async downloadExcel() {
      let condition = this.isSearch ? this.searchCondition : {}
      delete condition.deptIds
      let res = await this.$http.post(
        '/usercenter-admin/import/exportCertBaseInfo',
        condition
      )
      let certList = res.data
      let excel = await import('./export-excel')
      excel.exportCert(certList)
    }
  },
  created() {}
}
</script>
<style scoped>
.row-bg {
  padding: 10px 0;
  background-color: #f9fafc;
}
</style>
